# 实现服务器端的程序
import socket
import urllib.request


def get_ip():
    """
    获取本机公网IP地址
    :return:
    """
    my_ip = urllib.request.urlopen('http://ip.42.pl/raw').read()
    return my_ip


host = '0.0.0.0'
port = 80

s = socket.socket()
s.bind((host, port))

while True:
    s.listen(5)
    connection, address = s.accept()
    request = connection.recv(1024)
    # 通过连接接收客户端发送过来的数据
    print("ip and request, {}".format(address))
    ip = get_ip()
    ip = str(ip, encoding='utf-8')
    response = "<h1>ip: %s</h1>" % ip
    connection.sendall(response.encode())
    connection.close()
